﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;

namespace AutoStar.ViewModel
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        // 返回一个Action委托，用于通知属性更改
        protected Action<PropertyChangedEventArgs> RaisePropertyChanged()
        {
            return args =>
            {
                if (PropertyChanged != null)
                    PropertyChanged.Invoke(this, args);
            };
        }

        // 通知属性更改的方法，使用CallerMemberName特性获取属性名称
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        // <summary>
        /// 用于设置属性值并通知属性更改
        /// </summary>
        /// <typeparam name="T">属性类型</typeparam>
        /// <param name="backingField">字段存储属性的值</param>
        /// <param name="value">要设置的值</param>
        /// <param name="propertyName">属性名称</param>
        protected void SetAndNotify<T>(ref T backingField, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(backingField, value)) return;

            backingField = value;
            OnPropertyChanged(propertyName);
        }

        protected bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
            {
                return false;
            }

            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        public bool? ShowDialog(object viewModel)
        {
            Window window = new Window();
            window.DataContext = viewModel;

            return window.ShowDialog();
        }
        public delegate void CloseWindowEventHandler();
        public event CloseWindowEventHandler RequestClose;

        // 在需要关闭窗体时调用此方法
        protected virtual void OnRequestClose()
        {
            RequestClose?.Invoke();
        }
    }
}
